package server;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import serverPresentation.LoginMenu;
import serverPresentation.MainMenu;
import threads.ConnectionInitiatorThread;

public class CertcopServer {

	static{
		Security.addProvider(new BouncyCastleProvider());
	};

	private ConnectionInitiatorThread _connectionThread;
	private MainMenu _mainMenu;

	public CertcopServer(){
		new ServerData();	
	}

	private void run(){

		LoginMenu login = new LoginMenu();
		login.setVisible(true);

		boolean logon = ServerData.getServerData().isLoggedOn();

		while(!logon){
			logon = ServerData.getServerData().isLoggedOn();
		}		
		
		openMainMenu();	

		_connectionThread = new ConnectionInitiatorThread();	
		_connectionThread.start();		
	}
	
	private void openMainMenu(){
		_mainMenu = ServerData.getServerData().getMainMenu();
		
		_mainMenu.setVisible(true);
		
		PopupMenu popup = new PopupMenu();		
		MenuItem exit = new MenuItem("Sair");
		popup.add(exit);
		
		Image im = Toolkit.getDefaultToolkit().getImage("images/security-icon.gif");
		TrayIcon trayIcon = new TrayIcon(im);
		trayIcon.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				_mainMenu.setVisible(true);				
			}
		});
		
		exit.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				ServerData.getServerData().getMainMenu().dispose();
				ServerData.getServerData().setOffline();
			}
			
		});
		
		SystemTray tray = SystemTray.getSystemTray();		
		trayIcon.setPopupMenu(popup);
		try {
			tray.add(trayIcon);
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args){
		CertcopServer certcopServer = new CertcopServer();
		certcopServer.run();
	}
}
